package com.ruoyi.business.service.impl;

import com.ruoyi.business.service.IprocessService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

@Service
public class IprocessServiceImpl implements IprocessService {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;

    @Override
    public Deployment deploy(String filePath) throws FileNotFoundException {
        Deployment deployment = null;
        //bpmn / zip
        if (filePath.endsWith("zip")) {
            InputStream stream;
            ZipInputStream inputStream = new ZipInputStream(new FileInputStream(filePath));
            deployment = repositoryService.createDeployment()
                    .addZipInputStream(inputStream)
                    .deploy();
        } else {
            deployment = repositoryService.createDeployment()
                    .addInputStream(filePath, new FileInputStream(filePath))
                    .deploy();
        }
        return deployment;
    }

    @Override
    public ProcessDefinition getProcessDefinitionByDeploymentId(String deploymentId) {
        return repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
    }

    @Override
    public InputStream getBpmnInputStream(String deploymentId) {
        //获取流程
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        //D:/ruoyi/uploadPath/2021/07/19/91241233-f6b9-40b3-bd2d-7a15564a19d9.bpmn
        System.out.println(processDefinition.getResourceName());
        //传入部署id,bpmn文件名,可以获取到bpmn输入流信息
        return repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
    }

    @Override
    public InputStream getProcessImg(String deploymentId) {
        //获取流程定义id
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId).singleResult();
        //获取bpmnModel,主要描述节点,连线的信息
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        //定义绘制图形对象
        DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        //参数一:bpmnModel流程图 参数二:需要高亮的节点集合 参数二:需要高亮的连线集合
        InputStream inputStream = processDiagramGenerator.generateDiagram(bpmnModel, Collections.EMPTY_LIST,
                Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public ProcessInstance startProcessInstance(String definitionKey, String businessKey, Map<String, Object> variables) {
        return runtimeService.startProcessInstanceByKey(definitionKey, businessKey, variables);
    }

    @Override
    public Task getTaskByProcessInstanceId(String processInstanceId) {
        return taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public void addCandidateUser(Task currentTask, Long userId) {
        taskService.addCandidateUser(currentTask.getId(), String.valueOf(userId));
    }

    @Override
    public List<String> getActiveActivityIds(String instanceId) {
        return runtimeService.getActiveActivityIds(instanceId);
    }

    @Override
    public InputStream getProcessImage(String instanceId, List<String> activeActivityIds, List<String> emptyList) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).singleResult();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        InputStream inputStream = generator.generateDiagram(bpmnModel, activeActivityIds, emptyList,
                "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public void deleteProcessInstance(String instanceId) {
        runtimeService.deleteProcessInstance(instanceId, "撤销申请");
    }

    @Override
    public Long getTodoTaskCount(String definitionKey, String userId) {
        return taskService.createTaskQuery().processDefinitionKey(definitionKey).taskCandidateUser(userId).count();
    }

    @Override
    public List<Task> selectTodoTaskList(String definitionKey, String userId, Integer startNum, Integer pageSize) {
        return taskService.createTaskQuery()
                .processDefinitionKey(definitionKey)
                .taskCandidateUser(userId)
                .orderByTaskCreateTime()
                .asc()
                .listPage(startNum, pageSize);
    }

    @Override
    public ProcessInstance getProcessInstanceById(String processInstanceId) {
        return runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public Task getTaskByTaskId(String taskId) {
        return taskService.createTaskQuery().taskId(taskId).singleResult();
    }

    @Override
    public void claimAndComplete(Task task, String userId, Boolean auditStatus, String comment) {
        String commentStr = auditStatus ? "[同意]" : "[拒绝]";
        commentStr += comment;
        //给当前任务添加批注信息
        taskService.addComment(task.getId(), task.getProcessInstanceId(), commentStr);
        //认领任务
        taskService.claim(task.getId(), userId);
        //执行任务,把流程变量传入
        taskService.setVariable(task.getId(),task.getTaskDefinitionKey(),auditStatus);
        taskService.complete(task.getId());
    }

    @Override
    public void claimAndComplete(Task task, String userId, String comment) {
        //给当前任务添加批注信息
        taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
        //认领任务
        taskService.claim(task.getId(), userId);
        //完成任务
        taskService.complete(task.getId());
    }

    @Override
    public void setVariable(String taskId, String key, long value) {
        taskService.setVariable(taskId, key, value);
    }

    @Override
    public long getHistoricTaskCount(String definitionKey, String userId) {
        return historyService.createHistoricTaskInstanceQuery()
                .processDefinitionKey(definitionKey)
                .taskAssignee(userId)
                .finished()
                .count();
    }

    @Override
    public List<HistoricTaskInstance> selectDoneTaskList(String definitionKey, String userId, Integer startNum, Integer pageSize) {
        return historyService.createHistoricTaskInstanceQuery()
                .processDefinitionKey(definitionKey)
                .taskAssignee(userId)
                .finished()
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .listPage(startNum, pageSize);
    }

    @Override
    public HistoricProcessInstance getHistoricProcessInstanceById(String processInstanceId) {
        return historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public List<HistoricActivityInstance> selectHistoryActivityList(String instanceId) {
        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery()
                .activityType("userTask")
                .processInstanceId(instanceId)
                .finished()
                .orderByHistoricActivityInstanceEndTime()
                .desc().list();
        return list;
    }

    @Override
    public String getComment(String taskId) {
        List<Comment> taskComments = taskService.getTaskComments(taskId);
        if (taskComments != null && taskComments.size() > 0) {
            return taskComments.get(0).getFullMessage();
        }
        return "";
    }
}
